import { View, Text, Image, Input, Radio } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import classNames from 'classnames'
import axios from '@/request/index'
import { useWebStore } from '@/store/web'
import { useRichStore } from '@/store/rich'

function PageContent() {

  // const selector = ['广州市'];
  // const selectorYM = ['百白破', '脊髓灰质', 'HPV', '卡介', '流感', '甲肝', '狂犬', '水痘', '乙肝', '破伤风'];

  const [newsList, setNewsList] = useState<any[]>([]);
  const [zcList, setZcList] = useState<any[]>([]);
  const [knowledgeList, setKnowledgeList] = useState<any[]>([]);
  // const [selectorChecked, setSelectorChecked] = useState('广州市');
  const [searchChecked, setSearchChecked] = useState('');
  const [searchVisible, setSearchVisible] = useState(false);
  const [newsType, setNewsType] = useState(0);
  const [check, setCheck] = useState(false);
  const [loginVisible, setLoginVisible] = useState(false);

  const [searchList, setSearchList] = useState<any[]>([]);
  const { setUrl } = useWebStore()

  const { setRichContent } = useRichStore()

  const initKnowledge = async () => {
    const res = await axios.get('/catalog/homeVaccine', {
      params: {
      }
    })
    if (res && res.data) {
      setKnowledgeList(res.data)
    }
  }
  useDidShow(async () => {
    console.log('Page loaded.');
    if (!Taro.getStorageSync('token')) {
      setLoginVisible(true);
    }
    const newsRes = await axios.get('/catalog/homePage', {
      params: {
        type: 1,
      }
    })
    
    const zcRes = await axios.get('/catalog/homePage', {
      params: {
        type: 2,
      }
    })
    const searchRes = await axios.get('/catalog/searchVaccine', {
      params: {
      }
    })
    if (newsRes && newsRes.data) {
      setNewsList(newsRes.data.length > 3 ? newsRes.data.slice(0, 3) : newsRes.data)
    }
    if (zcRes && zcRes.data) {
      const arr = zcRes.data.length > 3 ? zcRes.data.slice(0, 3) : zcRes.data;
      setZcList(arr)
    }
    if (searchRes && searchRes.data) {
      setSearchList(searchRes.data)
    }
    initKnowledge();
  })

  const onClickLogin = async () => {
    if (!check) {
      Taro.showToast({
        title: '请先同意用户隐私政策',
        duration: 3000,
        icon: 'none'
      })
      return;
    }
    Taro.showLoading({
      title: '登录中...',
    });
    const resLogin = await Taro.login();
    if (resLogin.code) {
      const info = await Taro.getUserInfo();
      // 登录
      const res = await axios.post('/user/wxLogin', {
        code: resLogin.code,
        encryptedData: info.encryptedData,
        iv: info.iv,
      });
      if (res.data && res.data.token) {
        // debugger
        Taro.setStorageSync('token', res.data.token);
      } else {
        return;
      }
      Taro.showToast({
        title: '登录成功',
        duration: 3000,
      })
      setLoginVisible(false)

      // debugger
      // if (res.in) {

      // }
      // Taro.showModal({
      //   title: '授权提示',
      //   content:'是否授权允许获取用户信息?',
      //   async success(result) {
      //     if (result.confirm) {
      //       const info = await Taro.getUserProfile({
      //         desc: '用于获取用户信息',
      //       });
      //       debugger;

      //     }
      //   },
      // })
    }
    Taro.hideLoading();
  }

  // const onChange = (e) => {
  //   setSelectorChecked(selector[e.detail.value]);
  // }

  const onClickClose = () => {
    setLoginVisible(false);
  }
  const onClickProtocol = (e) => {
    e.stopPropagation();
    Taro.navigateTo({
      url: '/pages/Protocol/index'
    })
  }
  const onClickMoreNewsType = (e) => {
    e.stopPropagation();
    Taro.navigateTo({
      url: newsType === 0 ? '/package-home/pages/HomeNews/index' : '/package-home/pages/HomePolicy/index'
    })
  }

  const onClickMoreVacuum = () => {
    Taro.navigateTo({
      url: '/package-home/pages/HomeVacuum/index'
    })
  }
  const onClickFunnyAnswer = () => {
    Taro.navigateTo({
      url: '/package-home/pages/HomeFunnyAnswer/index'
    })
  }
  const onClickVideo = () => {
    Taro.navigateTo({
      url: '/package-home/pages/HomeVideo/index'
    })
  }
  const onClickKnowledge = () => {
    Taro.navigateTo({
      url: '/package-home/pages/HomeKnowledge/index'
    })
  }

  const onInputSearchChange = (e) => {
    setSearchChecked(e.detail.value);
    // if (searchTimerRef.current) {
    //   clearTimeout(searchTimerRef.current);
    //   searchTimerRef.current = null;
    // }
    // searchTimerRef.current = setTimeout(async () => {
    //   if (searchVisible) {
    //     const searchRes = await axios.get('/catalog/searchVaccine', {
    //       params: {
    //         name: e.detail.value,
    //       }
    //     })
    //     if (searchRes && searchRes.data) {
    //       setSearchList(searchRes.data)
    //     }
    //   }
    // }, 500)
  }

  const onSelectSearchItem = async (item: any) => {
    setSearchVisible(false)
    setSearchChecked('');

    const res = await axios.get('/catalog/getContentByCatalogId', {
      params: {
        id: item.id
      }
    })
    if (res && res.data) {
      setRichContent(res.data.content);
      Taro.navigateTo({
        url: '/package-home/pages/RichTextView/index'
      })
    }
    // setUrl(item.url)
    // Taro.navigateTo({
    //   url: `/package-home/pages/WebView/index`
    // })
  }

  const onClickCancelSearch = async () => {
    setSearchVisible(false);
    searchChecked && setSearchChecked('');
    const searchRes = await axios.get('/catalog/searchVaccine', {
      params: {
      }
    })
    if (searchRes && searchRes.data) {
      setSearchList(searchRes.data)
    }
  }
  const onClickSubmitSearch = async () => {
    const searchRes = await axios.get('/catalog/searchVaccine', {
      params: {
        name: searchChecked,
      }
    })
    if (searchRes && searchRes.data) {
      setSearchVisible(true);
      setSearchList(searchRes.data)
    }
  }

  const onClickBanner = () => {
    setUrl('https://mp.weixin.qq.com/s?__biz=Mzg3OTUyMDU5Nw==&mid=2247483827&idx=1&sn=de13148ed8654f77243f021d15c39656&chksm=cf027f89f875f69fe32480f2b06d6d48feae9862b680ba18d4a36def6a088172240cb9dab4ce#rd')
    Taro.navigateTo({
      url: '/package-home/pages/WebView/index'
    })
  }

  const onClickTool = (index: number) => {
    let url = '';
    if (index === 1) {
      url = 'https://www.gdzwfw.gov.cn/portal/help/login-sign-login-miniprogram.html';
    } else if (index === 2) {
      url = 'https://wsjkw.gd.gov.cn/gkmlpt/mindex';
    } else {
      url = 'https://www.gzcdc.org.cn/';
    }
    setUrl(url);
    Taro.navigateTo({
      url: '/package-home/pages/WebView/index'
    })
  }

  const onClickNews = (item: any) => {
    setUrl(item.content);
    Taro.navigateTo({
      url: '/package-home/pages/WebView/index'
    })
  }
  const onClickVaccine = async (item: any) => {
    const res = await axios.get('/catalog/getContentByCatalogId', {
      params: {
        id: item.id
      }
    })
    if (res && res.data) {
      setRichContent(res.data.content);
      Taro.navigateTo({
        url: '/package-home/pages/RichTextView/index'
      })
    }
  }
  

  return (
    <View className='page min-h-screen bg-[rgba(143,201,255,0.78)] pt-16' style={{ paddingTop: 64 }}>
      <View className='header flex flex-row items-center justify-center relative w-full px-6'>
        {/* <Picker className='absolute left-6 top-0' mode='selector' range={selector} onChange={onChange}>
        </Picker> */}
        <View className='picker absolute left-2 top-0'>
          <Text className='text-[#000] text-[28px]'>广州市</Text>
          {/* <Image src={require('./images/arrow.png')} className='ml-1 w-[28px] h-[16px]' /> */}
        </View>
        <Text className='text-[40px]'>
          疫苗先知
        </Text>
      </View>
      <View className='relative px-2 flex flex-row items-center justify-between'>
        <Image 
          src={require('./images/search.png')} 
          onClick={onClickSubmitSearch}
         className='w-[36px] h-[36px] absolute left-5 top-2' />
        <Input
          onInput={onInputSearchChange}
          onFocus={() => setSearchVisible(true)}
          onConfirm={onClickSubmitSearch}
          // onBlur={() => setSearchVisible(false)}
          placeholder='搜索'
          value={searchChecked}
          type='text'
          className='flex-1 bg-[rgba(0,0,0,0.08)] pl-[60px] h-[72px] rounded-[10px] overflow-hidden' />
        {/* {
          searchVisible &&
          <View className='text-[#0071FF] text-[28px] ml-3' onClick={onClickCancelSearch}>
            取消
          </View>
        } */}
      </View>
      <View className='px-4 pb-safe-offset-20'>
        <View className='banner mt-3'>
          <Image onClick={onClickBanner} src={require('./images/banner@2x.png')} className='w-full h-[160px]' />
        </View>
        <View className='tool mt-2'>
          <View className='p-3 bg-white rounded-lg overflow-hidden border-[1px] border-solid border-[#fff] box-border'>
            <View className='flex flex-row items-center justify-between'>
              <Text className='text-[#383838] text-[28px]'>疫苗工具推荐</Text>
              {/* <Image src={require('./images/right.png')} className='w-[12px] h-[20px]' /> */}
            </View>
            <View className='mt-3 flex flex-row items-center justify-between gap-4'>
              <View className='flex-1 relative' 
              onClick={() => onClickTool(1)}
              style={{
                background: 'linear-gradient(225deg, rgba(246, 247, 252, 1) 0%, rgba(235, 240, 255, 1) 100%);',
                borderRadius: '16px',
                padding: '16px 16px 32px 16px',
              }}>
                <View className='text-black text-[28px] leading-[28px]'>粤省事</View>
                <View className='text-[#808080] text-[20px] leading-[20px] mt-1'>疫苗预约</View>
                <Image src={require('./images/card1.png')} className='w-[64px] h-[56px] absolute right-0 bottom-0' />
              </View>
              <View className='flex-1 relative' 
              onClick={() => onClickTool(2)}
              style={{
                background: 'linear-gradient(212.23deg, #F2FBFF 0%, #E2F4FF 100%);',
                borderRadius: '16px',
                padding: '16px 16px 32px 16px',
              }}>
                <View className='text-black text-[28px] leading-[28px]'>粤健通</View>
                <View className='text-[#808080] text-[20px] leading-[20px] mt-1'>疫苗预约</View>
                <Image src={require('./images/card2.png')} className='w-[48px] h-[60px] absolute right-0 bottom-0' />
              </View>
              <View className='flex-1 relative' 
              onClick={() => onClickTool(3)}
              style={{
                background: 'linear-gradient(155.51deg, #DFF9FF 0%, #F8FFFF 100%);',
                borderRadius: '16px',
                padding: '16px 16px 32px 16px',
              }}>
                <View className='text-black text-[28px] leading-[28px]'>广州疫苗</View>
                <View className='text-[#808080] text-[20px] leading-[20px] mt-1'>疫苗预约</View>
                <Image src={require('./images/card3.png')} className='w-[64px] h-[68px] absolute right-0 bottom-0' />
              </View>
            </View>
          </View>
        </View>
        <View className='news mt-3 bg-white rounded-lg overflow-hidden'>
          <View className='flex justify-between items-center'>
            <View className={classNames('h-[72px] flex-1 text-center leading-[72px]', newsType === 1 ? "rounded-tr-[5px] rounded-br-[65px]" : '')}
              onClick={() => setNewsType(0)}
              style={{
                background: newsType === 0 ? '#fff' : 'linear-gradient(90deg, #FFFFFF 0%, #EDEFF2 100%);'
              }}>
              新闻
            </View>
            <View className={classNames('h-[72px] flex-1 text-center leading-[72px]', newsType === 0 ? "rounded-tl-[5px] rounded-bl-[65px]" : '')}
              onClick={() => setNewsType(1)}
              style={{
                background: newsType === 1 ? '#fff' : 'linear-gradient(90deg, #EDEFF2 0%, #FFFFFF 100%);'
              }}>
              政策
            </View>
          </View>
          <View className='flex flex-col justify-center pt-5 bg-white'>
            {
              (newsType === 0 ? newsList : zcList).map((item, index) => {
                return (
                  <View onClick={() => onClickNews(item)} key={index} className='flex flex-row items-center mt-8 bg-white px-[30px] first:mt-0'>
                    <Image src={item.cover} className='bg-[#A6A6A6] rounded-lg overflow-hidden w-[106px] h-[62px]' />
                    <View className='flex-1 flex flex-row items-center'>
                      <View className={classNames('w-[6px] h-[64px] ml-6 rounded-[3px]', 'bg-[#C8C9CC]')} />
                      <View className='flex-1 flex flex-col ml-2'>
                        <Text className='text-[28px] text-[#2F3033] line-clamp-1 leading-[28px]'>{item.title}</Text>
                        <Text className='text-[20px] text-[#808080] mt-2 leading-[20px]'>来源：{item.author}</Text>
                      </View>
                    </View>
                  </View>
                )
              })
            }
          </View>
          <View className='text-[24px] text-[#939599] leading-6 text-center py-4'
            onClick={onClickMoreNewsType}>
            查看更多
          </View>
        </View>
        <View className='knowledge mt-3 bg-white rounded-lg overflow-hidden px-4 py-[14px]'>
          <View className='text-[#6E7AFF] text-center text-[32px] font-black'>科普专区</View>
          <View className='mt-[30px] flex flex-row gap-4'>
            <View className='flex-1 flex flex-col'>
              <View className='p-3 relative'
                onClick={onClickKnowledge}
                style={{
                  background: 'linear-gradient(180deg, #FEFAFA 0%, #FFF1F1 100%)'
                }}>
                <View className='text-[28px] text-black'>疾病知识</View>
                <View className='text-[16px] text-[#383838] leading-4 mt-1'>守护你我健康</View>
                <View className='flex flex-row items-center mt-2'>
                  <Text className='text-[#FF4040] text-[24px] leading-6'>去领取</Text>
                  <Image src={require('./images/right_red.png')} className='w-[12px] h-[20px] ml-2' />
                </View>
                <Image src={require('./images/knowledge.png')} className='w-[96px] h-[112px] absolute bottom-0 right-3' />
              </View>
              <View className='mt-[28px] flex flex-row items-center justify-between gap-2'>
                <View
                  onClick={onClickVideo}
                  className='flex-1 py-3 bg-[#F8F9FB] rounded-lg overflow-hidden flex flex-col items-center justify-center'>
                  <Image className='w-[54px] h-[56px]' src={require('./images/video.png')} />
                  <Text className='text-[24px] text-[#383838]'>视频</Text>
                </View>
                <View
                  onClick={onClickFunnyAnswer}
                  className='flex-1 py-3 bg-[#F8F9FB] rounded-lg overflow-hidden flex flex-col items-center justify-center'>
                  <Image className='w-[54px] h-[56px]' src={require('./images/answer.png')} />
                  <Text className='text-[24px] text-[#383838]'>趣味答题</Text>
                </View>
              </View>
            </View>
            <View className='flex-1 rounded-lg overflow-hidden'>
              <View className='p-2'
                style={{
                  // background: 'linear-gradient(217.68deg, #FFF3EB 0%, #FFDAB6 100%);',
                  background: 'linear-gradient(180deg, #FFDAB6 0%, #F8F9FB 30.6%, #F8F9FB 100%)'
                  // filter: 'blur(44px)',
                }}>
                <View className='flex flex-row items-end gap-2 pt-3'>
                  <View className='flex flex-row items-end'>
                    <Text className='text-[28px] text-[#000] leading-[28px]'>疫苗知识</Text>
                    <Image className='w-[20px] h-[24px] ml-1' src={require('./images/fire.png')} />
                  </View>
                  <View className='text-[16px] text-[#383838] leading-[16px]'>为健康保驾护航</View>
                </View>
                <View className='flex flex-row items-center justify-between mt-6 gap-3'>
                  <View className='flex-1 relative py-[30px] bg-white rounded-lg overflow-hidden flex items-center justify-center'
                  onClick={() => onClickVaccine(knowledgeList[0])}>
                    <View className='text-[#383838] text-[24px] leading-6 z-10'>{knowledgeList.length ? knowledgeList[0].name : '狂犬疫苗'}</View>
                    <Image src={require('./images/knowledge1.png')} className="absolute -top-4 -right-4 w-[114px] h-[162px]" />
                  </View>
                  <View className='flex-1 relative py-[30px] bg-white rounded-lg overflow-hidden flex items-center justify-center'
                  onClick={() => onClickVaccine(knowledgeList[1])}>
                    <View className='text-[#383838] text-[24px] leading-6 z-10'>{knowledgeList.length > 1 ? knowledgeList[1].name : '卡介疫苗'}</View>
                    <Image src={require('./images/knowledge2.png')} className="absolute -top-4 -right-4 w-[114px] h-[162px]" />
                  </View>
                </View>
                <View className='flex flex-row items-center justify-between mt-4 gap-3'>
                  <View className='flex-1 relative py-[30px] bg-white rounded-lg overflow-hidden flex items-center justify-center'
                  onClick={() => onClickVaccine(knowledgeList[2])}>
                    <View className='text-[#383838] text-[24px] leading-6 z-10'>{knowledgeList.length > 2 ? knowledgeList[2].name : '水痘疫苗'}</View>
                    <Image src={require('./images/knowledge3.png')} className="absolute -top-4 -right-4 w-[114px] h-[162px]" />
                  </View>
                  <View className='flex-1 relative py-[30px] bg-white rounded-lg overflow-hidden flex items-center justify-center'
                    onClick={onClickMoreVacuum}>
                    <View className='flex flex-row items-center justify-center z-10'>
                      <Text className='text-[#383838] text-[24px] leading-6'>更多</Text>
                      <Image src={require('./images/more.png')} className='w-[6px] h-[10px] ml-1' />
                    </View>
                    <Image src={require('./images/knowledge4.png')} className="absolute -top-4 -right-4 w-[114px] h-[162px]" />
                  </View>
                </View>
              </View>
            </View>
          </View>
        </View>
      </View>
      {
        loginVisible &&
        <View className='fixed top-0 left-0 right-0 bottom-0 flex items-center justify-center bg-[rgba(0,0,0,0.5)]'>
          <View className='bg-white py-4 px-8 relative flex flex-col items-center rounded-2xl overflow-hidden'>
            <Image src={require('./images/close.png')} className='w-[32px] h-[32px] absolute right-2 top-2' onClick={onClickClose} />
            <Image src={require('./images/test.png')} className='w-[250px] h-[210px]' />
            <View
              onClick={onClickLogin}
              className='mt-3 bg-[#5C6AFE] w-[350px] h-[80px] rounded-lg overflow-hidden text-[#fff] text-[36px] text-center leading-[80px]'>
              微信登录授权
            </View>
            <View className='mt-2 flex flex-row items-center'>
              <Radio value='1' checked={check} onClick={() => setCheck(!check)}>
                <Text className='text-[#4D4646] text-[25px]'>请阅读并勾选</Text>
              </Radio>
              <Text className='text-[#060CBD] text-[24px] leading-[24px] pt-1' onClick={onClickProtocol}>{'<用户隐私协议条款>'}</Text>
            </View>
          </View>
        </View>
      }
      {
          searchVisible && 
          <View className='fixed z-50 left-0 right-0 top-[236px] bottom-0 bg-[rgba(0,0,0,0.5)] flex items-start justify-center'
          onClick={onClickCancelSearch}>
            <View className='min-h-[600px] w-full bg-white px-3 rounded-lg' >
              <View className='flex flex-row items-center justify-between py-3 border-b-[1px] border-solid border-[#E5E6EB]'>
                <Text onClick={onClickCancelSearch}>取消</Text>
                <Text>选择疫苗</Text>
                <Text onClick={onClickCancelSearch}>确定</Text>
              </View>
              <View className='grid grid-cols-3 gap-3 mt-3 pb-3'>
                {
                  searchList.map((item, index) => {
                    return (
                      <View 
                      key={index} 
                      onClick={() => onSelectSearchItem(item)}
                      className='text-center line-clamp-1'>{item.name}</View>
                    )
                  })
                }
              </View>
            </View>
          </View>
        }
    </View>
  )
}

export default PageContent